package
{
	import com.phantasy.Style;
	import com.phantasy.common.GlobalObjectManager;
	import com.phantasy.globals.GameConfig;
	import com.phantasy.loaders.CommonLocator;
	import com.phantasy.loaders.ResourcePool;
	import com.phantasy.loaders.batchLoader.BatchEvent;
	import com.phantasy.loaders.batchLoader.BatchLoader;
	import com.phantasy.loaders.gameLoader.ResourceItem;
	import com.phantasy.managers.Dispatch;
	import com.phantasy.managers.LayerManager;
	import com.phantasy.managers.ReSizeManager;
	import com.phantasy.modules.ModuleCommand;
	import com.phantasy.modules.ModuleFactory;
	import com.phantasy.modules.buff.BuffModule;
	import com.phantasy.modules.mission.MissionNPCConfig;
	import com.phantasy.modules.npc.NPCDataManager;
	import com.phantasy.modules.pet.config.PetConfig;
	import com.phantasy.modules.skill.SkillDataManager;
	import com.phantasy.modules.system.SystemConfig;
	import com.phantasy.net.SocketCommand;
	import com.phantasy.net.connection.Connection;
	import com.phantasy.proto.m_auth_key_toc;
	import com.phantasy.proto.m_role2_detail_toc;
	import com.phantasy.proto.m_role2_detail_tos;
	import com.phantasy.scene.WorldManager;
	import com.phantasy.scene.sceneManager.LoopManager;
	import com.phantasy.scene.sceneUnit.configs.MonsterConfig;
	
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.ui.ContextMenu;
	import flash.ui.ContextMenuItem;
	import flash.utils.ByteArray;
	
	public class Main extends Sprite
	{
		private static var _instance:Main;
		private var _batchLoader:BatchLoader;
		public function Main()
		{
			this.addEventListener(Event.ADDED_TO_STAGE,this.init);
		}
		
		public static function getInstance():Main
		{
			if(Main._instance==null){
				Main._instance = new Main();
			}
			
			return Main._instance;
		} 
		
		/**
		 *初始化账号信息 此时会根据角色所在的地图id加载具体地图的mcms文件
		 * @param message
		 * 
		 */		
		public function initAuthInfo(message:m_auth_key_toc):void
		{
			if (Connection.getInstance().isReConnect)
			{
				return;
			}
			if (this._batchLoader == null)
			{
				this._batchLoader = new BatchLoader();
			}
			
			GlobalObjectManager.getInstance().totaltm = message.totaltm;
			GlobalObjectManager.getInstance().passfcm = message.passfcm;
			this._batchLoader.addEventListener(BatchEvent.BATCH_ITEM_COMPLETE, this.onExtItemLoadComplete);
			this._batchLoader.addEventListener(BatchEvent.BATCH_COMPLETE, this.onExtComplete);
			var mapName:String = message.map_id.toString().substr(0, 2);
			var mapConfigURL:String = (("com/maps/mcm/" + mapName) + ".mcms");
			this._batchLoader.add(mapConfigURL, "地图配置");
			this._batchLoader.load();
		}
		
		private function init(event:Event):void
		{
			this.removeEventListener(Event.ADDED_TO_STAGE,this.init);
			ReSizeManager.init(this.parent.stage);
			LoopManager.init(this.parent.stage);
			//创建登陆模块
			ModuleFactory.createLoginModule();
			LayerManager.init(this,this.parent.stage);
			this.loadConfig();
		}
		
		/**
		 *加载配置 
		 * 
		 */		
		private function loadConfig():void
		{
			_batchLoader = new BatchLoader();
			this._batchLoader.addEventListener(BatchEvent.BATCH_ITEM_PROGRESS, this.onItemProgress);
			this._batchLoader.addEventListener(BatchEvent.BATCH_ITEM_COMPLETE, this.onItemComplete);
			this._batchLoader.addEventListener(BatchEvent.BATCH_ITEM_IO_ERROR, this.onItemIOError);
			this._batchLoader.addEventListener(BatchEvent.BATCH_COMPLETE, this.onBatchComplete);
			this._batchLoader.add(GameConfig.XML_LIB_URL, "游戏配置");
			this._batchLoader.add(GameConfig.UI_URL, "组件UI");
			this._batchLoader.add(GameConfig.VIEWUI_URL, "界面UI");
			this._batchLoader.add(GameConfig.NPC_DATA_URL, "NPC数据");
			this._batchLoader.add(GameConfig.POS_URL, "所有地图物品位置数据");
			this._batchLoader.add(GameConfig.MISSION_DATA_URL, "任务配置");
			this._batchLoader.add(GameConfig.MISSION_SETTING, "任务配置");
			this._batchLoader.add(GameConfig.WORDFILTER, "聊天配置");
			this._batchLoader.add(GameConfig.SOUND_URL, "声音资源");
			this._batchLoader.load();
		}
		
		private function onItemProgress(event:BatchEvent):void
		{
			GameLoading.getInstance().setItemPercent((("正在载入" + event.loadItem.data) + "："), event.data.bytesLoaded, event.data.bytesTotal);
		}
		
		private function onItemComplete(event:BatchEvent):void
		{
			var batchLoader:BatchLoader;
			GameLoading.getInstance().setTotalPercent((this._batchLoader.loadCount + 1), this._batchLoader.size);
			if(event.loadItem.type==ResourceItem.SWF){
				
				batchLoader = event.currentTarget as BatchLoader;
				ResourcePool.add(event.loadItem.url,batchLoader.decoder.contentLoaderInfo.applicationDomain);
				
			}else if(event.loadItem.url.substr((event.loadItem.url.length - 3), 3) == "jpg"){
				
				ResourcePool.add(event.loadItem.url, event.data.content.bitmapData);
				
			}else if(event.loadItem.url.substr((event.loadItem.url.length - 4), 4) == "mcms"){
				WorldManager.parseMcmBag(event.data);
			}
			
			this.initGameData(event.loadItem.url, event.data);
		}
		
		/**
		 *初始化游戏数据 
		 * @param url
		 * @param data
		 * 
		 */		
		private function initGameData(url:String,data:ByteArray):void
		{
			switch(url){
				case GameConfig.UI_URL:
					Style.getInstance().startInit();
					break;
				case GameConfig.XML_LIB_URL:
					CommonLocator.parseXMLFile(data);//解析系统配置
					MonsterConfig.init();
					PetConfig.init();
					SkillDataManager.init();
					BuffModule.init();
					MissionNPCConfig.init();
					WorldManager.setup();
					break;
				case GameConfig.MISSION_DATA_URL:
					break;
				case GameConfig.DEFLUT_BODY_TRANSPARENT:
					break;
				case GameConfig.NPC_DATA_URL:
					NPCDataManager.getInstance().initNpcData(data);
					break;
				case GameConfig.MISSION_SETTING:
					break;
				case GameConfig.POS_URL:
					break;
				case GameConfig.WORDFILTER:
					break;
			}
		}
		
		private function onItemIOError(event:BatchEvent):void
		{
			
		}
		
		private function onBatchComplete(event:BatchEvent):void
		{
			this._batchLoader.removeEventListener(BatchEvent.BATCH_ITEM_PROGRESS, this.onItemProgress);
			this._batchLoader.removeEventListener(BatchEvent.BATCH_ITEM_COMPLETE, this.onItemComplete);
			this._batchLoader.removeEventListener(BatchEvent.BATCH_ITEM_IO_ERROR, this.onItemIOError);
			this._batchLoader.removeEventListener(BatchEvent.BATCH_COMPLETE, this.onBatchComplete);
			
			this.createContextMenu();
			LayerManager.createLayers();
			ModuleFactory.createModules();
			this.dispatchEvent(new Event("WAIT_AUTH_INFO"));
		}
		
		private function createContextMenu():void
		{
			//创建鼠标右键菜单
		}
		
		private function onExtItemLoadComplete(event:BatchEvent):void
		{
			if (event.loadItem.url.substr((event.loadItem.url.length - 4), 4) == "mcms")
			{
				WorldManager.parseMcmBag(event.data);
			}
		}
		
		/**
		 *地图数据加载完成后获取角色完整信息 
		 * @param event
		 * 
		 */		
		private function onExtComplete(event:BatchEvent):void
		{
			GameLoading.getInstance().itemLabel = "正在获取角色完整信息";
			var getRoleDetail:m_role2_detail_tos = new m_role2_detail_tos();
			Connection.getInstance().sendMessage(getRoleDetail);
			Connection.getInstance().addSocketListener(SocketCommand.ROLE2_DETAIL, this.onRoleDetail);
		}
		
		private function onRoleDetail(message:m_role2_detail_toc):void
		{
			if(message.wait_sec>0){
				//如果服务器满了.弹出提示框让等待
			}else{
				GlobalObjectManager.getInstance().user = message.role_details;
				SystemConfig.serverTime = message.server_time;
				GameLoading.getInstance().destroy();
				
				Dispatch.dispatch(ModuleCommand.START_UP_SCENE);
			}
		}
		
	}
}